package Backend

import (
	"fmt"
	"gitee.com/zchunshan/d3auth"
	"github.com/json-iterator/go"
	"github.com/syyongx/php2go"
	"hello/controllers/Base"
	"hello/models"
	"hello/services/Action"
	"hello/wl"
	"strconv"
	"strings"
)

type OAuthController struct {
	Base.BaseController
	Action.OAuthAction

}
var githubAuth *d3auth.Auth_github

type Auth_conf struct {
	Appid  string
	Appkey string
	Rurl   string
}

//初始化加载配置文件 key
func init()  {
	githubConf:=&d3auth.Auth_conf{Appid: wl.C("Github::Appid"), Appkey: wl.C("Github::Appkey"), Rurl: wl.C("Github::Rurl")}
	githubAuth = d3auth.NewAuth_github(githubConf)
}


//获取登陆的URL
func (this *OAuthController) LoginUrl() {

	url:=githubAuth.Get_Rurl("state") //获取第三方登录地址
	fmt.Println(url)
	this.AjaxSuccess(url)

}


//github登陆的Action
func (this *OAuthController) AuthLogin() {
	code:=this.GetString("code")
	token, err := githubAuth.Get_Token(code) //回调页收的code 获取token
	if err != nil {
		fmt.Print(err, "\r\n")
		this.AjaxError("已经登陆过了1")
		return
	}

	jsonText, err := githubAuth.Get_User_Info(token) //获取用户信息 userinfo 是一个json字符串返回
	if err != nil {
		fmt.Print(err)
		this.AjaxError("已经登陆过了2")
	}
	json := jsoniter.ConfigCompatibleWithStandardLibrary
	reader := strings.NewReader(jsonText)
	decoder := json.NewDecoder(reader)
	params := make(map[string]interface{})
	err = decoder.Decode(&params)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%+v\n", params)
	}

	gitHubUser:=models.User{
		Username:params["name"].(string),
		Email:"github_"+params["login"].(string),
		Password:params["node_id"].(string),
		Tou:params["avatar_url"].(string),
		Access_token:php2go.Md5(params["node_id"].(string)),
		Salt:strconv.FormatFloat(params["id"].(float64), 'E', -1, 32),
		Usertype:1}

	//获取github头像上传到七牛
	imageName:=this.GetHttpImg(gitHubUser.Tou)

	qiImagePath:=QiNiuUpload(wl.UploadPath+imageName,imageName)

	gitHubUser.Tou=wl.C("QiNiu::Host")+qiImagePath

	gitHubUser.FindByNode()

	//没有找到才创建用户
	if php2go.Empty(gitHubUser.Id){
		gitHubUser.CreateUser()
		wl.RedisSet(gitHubUser.Access_token,gitHubUser,30)
		this.AjaxSuccess(gitHubUser.Access_token)
	}else{
		Access_token:=gitHubUser.Access_token

		go func() {
			//登陆完修改Token
			gitHubUser.ReloadAccessToken()
		}()

		wl.RedisSet(Access_token,gitHubUser,30)
		this.AjaxSuccess(Access_token)
	}


}


func (this *OAuthController) Github() {

	code:=this.GetString("code")
	token, err := githubAuth.Get_Token(code) //回调页收的code 获取token
	if err != nil {
		fmt.Print(err, "\r\n")
		return
	}

	userinfo, err := githubAuth.Get_User_Info(token) //获取用户信息 userinfo 是一个json字符串返回
	if err != nil {
		fmt.Print(err)
	}

	fmt.Print(userinfo)

	this.AjaxSuccess(userinfo)

}


// @router /test/des [get]
func (this *OAuthController) Index() {


	infoData :="我的天我是谁！"
	var infoKey string="12123123"
	var str []byte=[]byte(infoData)
	code,err:=DesEncrypt(str,[]byte(infoKey))
	baseCode:=php2go.Base64Encode(string(code))
	fmt.Println(baseCode)
	fmt.Println(err)

	baseDecode,_:= php2go.Base64Decode(baseCode)
	jieCode,err2:=DesDecrypt([]byte(baseDecode),[]byte(infoKey))
	fmt.Println(err2)
	this.Data["json"] =string(jieCode)

	this.Log.Write(infoData)

	this.ServeJSON()

}
// @router /test/qq [get]
func (this *OAuthController) QQ(){
	qqconf := &d3auth.Auth_conf{Appid: "101509113", Appkey: "4a83fae41b796e2d2c28f4ada47334e1", Rurl: "http://wlphp.cn/back"}


	qqAuth := d3auth.NewAuth_qq(qqconf)

	login_url:=qqAuth.Get_Rurl("state")
	//fmt.Print() //获取第三方登录地址
	fmt.Println(login_url)
	this.AjaxError(login_url)

	token, err := qqAuth.Get_Token("code")  //回调页收的code 获取token

	fmt.Println(err)


	me, err := qqAuth.Get_Me(token)  //获取第三方id

	//Client_ID string `json:"client_id"`
	//OpenID    string `json:"openid"`
	wbAuth:= d3auth.NewAuth_qq(qqconf)
	userinfo, _ := wbAuth.Get_User_Info(token, me.OpenID)  //获取用户信息 userinfo 是一个json字符串返回
	fmt.Println(userinfo)
	this.AjaxSuccess(login_url)
}

func (this *OAuthController) QQLogin(){
	qqconf := &d3auth.Auth_conf{Appid: "101509113", Appkey: "4a83fae41b796e2d2c28f4ada47334e1", Rurl: "http://wlphp.cn/back"}


	qqAuth := d3auth.NewAuth_qq(qqconf)

	//login_url:=qqAuth.Get_Rurl("state")
	//fmt.Print() //获取第三方登录地址
	//fmt.Println(login_url)
	//this.AjaxError(login_url)

	token, err := qqAuth.Get_Token("code")  //回调页收的code 获取token

	token=this.GetPost("code").(string)
	fmt.Println(err)

	me, err := qqAuth.Get_Me(token)  //获取第三方id


	fmt.Println(err)
	this.AjaxSuccess(me)


	//Client_ID string `json:"client_id"`
	//OpenID    string `json:"openid"`
	//wbAuth:= d3auth.NewAuth_qq(qqconf)
	userinfo, _ := qqAuth.Get_User_Info(token, me.OpenID)  //获取用户信息 userinfo 是一个json字符串返回
	fmt.Println(userinfo)

	//this.AjaxSuccess(login_url)
}




// @router /login/test [get]
func (this *OAuthController) Test(){
	json := jsoniter.ConfigCompatibleWithStandardLibrary
	jsonText:= `{"login":"yymmhh","id":34824081,"node_id":"MDQ6VXNlcjM0ODI0MDgx","avatar_url":"https://avatars3.githubusercontent.com/u/34824081?v=4","gravatar_id":"","url":"https://api.github.com/users/yymmhh","html_url":"https://github.com/yymmhh","followers_url":"https://api.github.com/users/yymmhh/followers","following_url":"https://api.github.com/users/yymmhh/following{/other_user}","gists_url":"https://api.github.com/users/yymmhh/gists{/gist_id}","starred_url":"https://api.github.com/users/yymmhh/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/yymmhh/subscriptions","organizations_url":"https://api.github.com/users/yymmhh/orgs","repos_url":"https://api.github.com/users/yymmhh/repos","events_url":"https://api.github.com/users/yymmhh/events{/privacy}","received_events_url":"https://api.github.com/users/yymmhh/received_events","type":"User","site_admin":false,"name":"万隆","company":null,"blog":"","location":null,"email":null,"hireable":null,"bio":null,"public_repos":9,"public_gists":0,"followers":0,"following":0,"created_at":"2017-12-25T02:08:44Z","updated_at":"2019-05-05T02:12:18Z"}`
	reader := strings.NewReader(jsonText)
	decoder := json.NewDecoder(reader)
	params := make(map[string]interface{})
	err := decoder.Decode(&params)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%+v\n", params)
	}

	gitHubUser:=models.User{
							Username:params["name"].(string),
							Email:"github_"+params["login"].(string),
							Password:params["node_id"].(string),
							Tou:params["avatar_url"].(string),
							Access_token:php2go.Md5(params["node_id"].(string)),
							Salt:strconv.FormatFloat(params["id"].(float64), 'E', -1, 32),
							Usertype:1}

	gitHubUser.FindByNode()

	//没有找到才创建用户
	if php2go.Empty(gitHubUser.Id){
		gitHubUser.CreateUser()
	}else{
		this.AjaxSuccess(gitHubUser.Access_token)
	}

	this.AjaxSuccess(params)

}





